package com.atguigu.gulimall.order.listener;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVO;
import com.mysql.cj.xdevapi.JsonArray;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 监听支付回调消息
 *
 * @author meiyn
 * @date 2021/7/26 11:45
 */
@RestController
public class OrderPayedListener {
    @Resource
    private OrderService orderService;

    @Resource
    private AlipayTemplate alipayTemplate;

    /**
     * 支付宝异步回调
     *
     * @param request
     * @return
     */
    @PostMapping("/alipay/paid/notify")
    public String paidNotify(PayAsyncVO payAsyncVO, HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        System.out.println("支付宝-支付成功异步回调数据。。。。data："+JSON.toJSONString(requestParams));
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipayPublicKey(),
                alipayTemplate.getCharset(), alipayTemplate.getSignType()); //调用SDK验证签名


        if (signVerified) {
            System.out.println("签名验证成功");
            // 添加交易流水、修改订单状态
            String result = orderService.handlePayResult(payAsyncVO);
            return result;
        } else {
            System.out.println("签名验证失败");
            return "error";
        }
    }
}
